<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

// 获取POST数据
$action = $_POST['action'] ?? '';
$orderIds = $_POST['order_ids'] ?? [];
$status = $_POST['status'] ?? '';
$settlementType = $_POST['settlement_type'] ?? 'commission';
$settlementAmount = $_POST['settlement_amount'] ?? null;
$settlementInfo = $_POST['settlement_info'] ?? '';

// 修改订单ID解析部分：
if (isset($_POST['order_ids']) && is_string($_POST['order_ids'])) {
    $orderIds = json_decode($_POST['order_ids'], true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        // 如果不是JSON格式，尝试其他方式解析
        $orderIds = is_array($_POST['order_ids']) ? $_POST['order_ids'] : [$orderIds];
    }
} else {
    $orderIds = $_POST['order_ids'] ?? [];
}

if (empty($orderIds) || !is_array($orderIds)) {
    echo json_encode(['success' => false, 'message' => '请选择要操作的订单']);
    exit;
}

// 确保所有订单ID都是整数
$orderIds = array_map('intval', $orderIds);
$orderIds = array_filter($orderIds); // 移除0值

$db = getDB();
$successCount = 0;
$errorCount = 0;
$errors = [];

// 处理结算截图上传
$settlementScreenshots = [];
if ($status == 'settled' && isset($_FILES['settlement_screenshot']) && $_FILES['settlement_screenshot']['error'] === UPLOAD_ERR_OK) {
    $uploadResult = uploadFile($_FILES['settlement_screenshot'], 'settlement_screenshot');
    if ($uploadResult['success']) {
        $settlementScreenshots[] = $uploadResult['filename'];
    }
}

// 按用户分组处理订单
$ordersByUser = [];
foreach ($orderIds as $orderId) {
    $orderId = intval($orderId);
    if ($orderId <= 0) continue;
    
    // 获取订单信息
    $stmt = $db->prepare("SELECT o.*, u.username FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch();
    
    if (!$order) {
        $errors[] = "订单 {$orderId} 不存在";
        $errorCount++;
        continue;
    }
    
    if (!isset($ordersByUser[$order['user_id']])) {
        $ordersByUser[$order['user_id']] = [];
    }
    $ordersByUser[$order['user_id']][] = $order;
}

// 处理每个用户的订单
foreach ($ordersByUser as $userId => $userOrders) {
    try {
        $totalAmount = 0;
        $orderIdList = [];
        
        foreach ($userOrders as $order) {
            $orderId = $order['id'];
            
            // 计算结算金额
            $finalSettlementAmount = $settlementAmount;
            if (empty($finalSettlementAmount)) {
                if ($settlementType == 'commission') {
                    // 结本金 - 10%佣金示例
                    $finalSettlementAmount = $order['order_amount'] * 0.1;
                } else {
                    // 结本金+佣金
                    $finalSettlementAmount = $order['order_amount'];
                }
            }
            
            // 确定操作类型
            $operationType = '';
            if ($status == 'settled') {
                $operationType = ($settlementType == 'commission') ? 'settle_principal' : 'settle_commission';
            } elseif ($status == 'refunded') {
                $operationType = 'return';
            }
            
            // 开始事务
            $db->beginTransaction();
            
            try {
                // 更新订单
                $updateFields = [
                    'status' => $status,
                    'settlement_amount' => $finalSettlementAmount,
                    'settlement_info' => $settlementInfo,
                    'admin_id' => $_SESSION['user_id'],
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                
                // 根据状态设置相应字段
                if ($status == 'settled') {
                    $updateFields['is_registered'] = 1;
                    $updateFields['settlement_type'] = ($settlementType == 'commission') ? 'principal' : 'principal_commission';
                } elseif ($status == 'refunded') {
                    $updateFields['is_registered'] = 1;
                    $updateFields['is_returned'] = 1;
                }
                
                // 在处理每个订单的循环中，添加结算明细记录
                if ($status == 'settled') {
                    // 创建结算明细记录
                    if (!createSettlementDetail($settlementId, $orderId, $settlementType, $finalSettlementAmount, $settlementInfo, $settlementScreenshots, $_SESSION['user_id'])) {
                        throw new Exception('结算明细记录失败');
                    }
                }
                
                // 构建更新SQL
                $setParts = [];
                $params = [];
                foreach ($updateFields as $field => $value) {
                    $setParts[] = "{$field} = ?";
                    $params[] = $value;
                }
                $params[] = $orderId;
                
                $updateSql = "UPDATE orders SET " . implode(', ', $setParts) . " WHERE id = ?";
                $stmt = $db->prepare($updateSql);
                
                if ($stmt->execute($params)) {
                    // 记录操作
                    if ($operationType) {
                        $operationAmount = $finalSettlementAmount;
                        if (!$recordOrderOperation($orderId, $operationType, $operationAmount, $settlementInfo, $settlementScreenshots, $_SESSION['user_id'])) {
                            throw new Exception('操作记录失败');
                        }
                    }
                    
                    $successCount++;
                    
                    // 如果是结算状态，将订单汇总到用户待结账单
                    if ($status == 'settled') {
                        $totalAmount += $finalSettlementAmount;
                        $orderIdList[] = $orderId;
                    }
                    
                    $db->commit();
                } else {
                    throw new Exception("订单 {$orderId} 更新失败");
                }
                
            } catch (Exception $e) {
                $db->rollback();
                throw $e;
            }
        }
        
        // 创建或更新结算记录（仅对已结算的订单）
        if ($status == 'settled' && !empty($orderIdList)) {
            // 检查是否已存在待结算记录
            $stmt = $db->prepare("SELECT id, total_amount, order_ids FROM settlements WHERE user_id = ? AND status = 'pending'");
            $stmt->execute([$userId]);
            $existingSettlement = $stmt->fetch();
            
            if ($existingSettlement) {
                // 更新现有记录
                $existingOrderIds = json_decode($existingSettlement['order_ids'], true) ?: [];
                $mergedOrderIds = array_unique(array_merge($existingOrderIds, $orderIdList));
                $newTotalAmount = $existingSettlement['total_amount'] + $totalAmount;
                
                $stmt = $db->prepare("UPDATE settlements SET 
                                    total_amount = ?, 
                                    order_ids = ?,
                                    updated_at = NOW()
                                    WHERE id = ?");
                $stmt->execute([$newTotalAmount, json_encode($mergedOrderIds), $existingSettlement['id']]);
            } else {
                // 创建新记录
                $stmt = $db->prepare("INSERT INTO settlements (user_id, settlement_type, total_amount, order_ids, admin_id, status) VALUES (?, ?, ?, ?, ?, 'pending')");
                $stmt->execute([
                    $userId,
                    $settlementType,
                    $totalAmount,
                    json_encode($orderIdList),
                    $_SESSION['user_id']
                ]);
            }
        }
        
    } catch (Exception $e) {
        $errors[] = "用户 {$userId} 的订单处理出错: " . $e->getMessage();
        $errorCount += count($userOrders);
    }
}

$response = [
    'success' => $errorCount === 0,
    'message' => "操作完成：成功 {$successCount} 个，失败 {$errorCount} 个",
    'success_count' => $successCount,
    'error_count' => $errorCount,
    'errors' => $errors
];

echo json_encode($response);
?>